<template>
  <div class="login-wrap">
    <div class="ms-title">船舶计划申报系统</div>
    <div class="ms-login">
      <h2>登录</h2>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入用户名" class="phone"></el-input>
        </el-form-item>
        <el-form-item prop="password" >
          <el-input show-password placeholder="请输入密码" v-model="ruleForm.password"
                    @keyup.enter.native="submitForm('ruleForm')" class="newpwd"></el-input>
        </el-form-item>
        <el-form-item prop="imageCode" placeholder="验证码" class="code_box">
          <el-input v-model="ruleForm.imageCode" placeholder="请输入验证码" class="code"></el-input>
          <!--          <div>-->
          <img class="code_img" :src="codeImage" alt="" @click="changeCode()">
          <!--          </div>-->
        </el-form-item>
        <div class="login-pwd">
          <el-button type="text" @click="forgetpwd" class="forgetpwd">忘记密码？</el-button>
        </div>
        <div class="login-btn">
          <el-button type="primary" @click="submitForm('ruleForm')" :loading="submitLoad">登 录</el-button>
        </div>
        <!--   <p style="font-size:12px;line-height:30px;color:#999;">Tips : 用户名和密码随便填。</p> -->
      </el-form>
    </div>

  </div>
</template>

<script>
  import * as authService from '../../services/AuthService'
  import * as userService from '../../services/UserService'
  import Vue from 'vue'
  import Config from '@/config/index.js'
  // import _ from 'lodash'

  export default {
    data: function () {
      return {
        submitLoad: false,
        checked: false,
        msgcodeImg: '',
        captchaKey: '',
        apiPath: '',
        orgName: '',
        orgArray: Config.ORGANIZATIONS,
        serviceValid: false,
        ruleForm: {
          username: '',
          password: '',
          imageCode: ''
          // captcha: ''
        },
        rules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ],
          api: [
            {
              trigger: 'blur',
              validator: (rule, value, callback) => {
                if (!this.apiPath) {
                  return callback(new Error('请选择海事局'))
                }
                callback()
              }
            }
          ],
          imageCode: [
            {required: true, message: '请输入验证码', trigger: 'blur'}
          ]
        },
        codeImage: null,
        codeShow: true,
          isApply: false,
          apply: {
              applyUser: '',
              password: ''
          }
      }
    },
    created() {
      this.apiPath = window.apiPath
      if (this.apiPath === '/api' || this.apiPath === '/weifang') {
        this.serviceValid = true
      }
      if (localStorage.getItem('password') && localStorage.getItem('username')) {
        this.ruleForm.username = localStorage.getItem('username')
        this.ruleForm.password = localStorage.getItem('password')
      }
      this.changeCode()
    },
    mounted() {
      this.changeCode()
    },
    methods: {
      changeCode(isFlag) {
        let num = Math.random()
        if (!this.apiPath) {
          this.$set(this, 'codeImage', '/api/imageCode?' + num)
        } else {
          this.$set(this, 'codeImage', this.apiPath + '/imageCode?' + num)
        }
      },
      // changeMsg() {
      //   this.captchaKey = new Date().getTime()
      //   this.$axios.get("/CaptchaGetCaptcha", {
      //     params: {
      //       skey: localStorage.getItem('auth'),
      //       captchaKey: this.captchaKey
      //     }
      //   }).then((res) => {
      //     this.msgcodeImg = this.$config['imgUrl'] + res.data.content
      //   })
      // },
      orgChanged(val) {

        let org = this.orgArray.find(o => o.value === val)
        // console.log('val:::::', org)
        this.serviceValid = !!org.active
        this.orgName = org.name
        document.title = org.name + '动态监管指挥系统'
        window.apiPath = val
        this.changeCode()
      },
      forgetpwd() {
        this.$router.push('/forgot-pwd')
      },
      submitForm(formName) {
          let userObj = {
              applyUser: this.ruleForm.username,
              password: this.ruleForm.password,
              imageCode: this.ruleForm.imageCode
          }
          authService.applyUsers(this.ruleForm.username, this.ruleForm.password, this.ruleForm.imageCode).then(res => {
              if (res.status == 200 && res.data) {
                  this.$message({
                      message: '申请人登陆成功!',
                      type: 'success'
                  })
                  localStorage.setItem('token', res.data.password)
                  localStorage.setItem('userInfo', JSON.stringify(res.data))
                  localStorage.setItem('userName', userObj.applyUser)
                  this.$router.push('/')
              } else {
                  this.$message({
                      message: '用户名或密码填写错误!',
                      type: 'error'
                  })
              }
          }).catch(resp => {
              // console.log(resp)
              if (resp.status === 401) {
                  if (resp.data.detail.indexOf('validateCode') > -1) {
                      // this.$alert('登录失败，验证码不正确')
                  } else {
                      // this.$alert('登录失败，用户名或密码不正确')
                  }
                  this.submitLoad = false
              } else {
                  this.$alert('登录时发生错误，请稍候再试')
                  this.submitLoad = false
                  // console.log('login response:', resp)
              }
              // console.log('err', err)
          })
          return false
        let org = this.orgArray.find(o => o.value === this.apiPath)
        console.log('org::::', org)
        // if (!org.active) {
        //   return this.$alert('该分局系统即将开放，敬请期待')
        // }
        this.submitLoad = true
        const self = this
        self.$refs[formName].validate(valid => {
          if (!valid) {
            this.submitLoad = false
            return
          }

          // try {
          authService.login(this.ruleForm.username, this.ruleForm.password, this.ruleForm.imageCode, this.checked).then(ret => {
            localStorage.setItem('token', ret.id_token)
            userService.getMyInfo().then(info => {
              console.log('user info:', info)
              if (info.sysUser.organiza.businessOrg === 6) {
                info.sysUser.olevel = 1
              } else {
                info.sysUser.olevel = info.sysUser.organiza.level
              }
              localStorage.setItem('profile', JSON.stringify(info.sysUser))
              localStorage.setItem('apiPath', this.apiPath)
              window.apiPath = this.apiPath
              Vue.prototype.$profile = info.sysUser
              this.$router.push('/')
              this.submitLoad = false
            })
          }).catch(resp => {
            // console.log(resp)
            if (resp.status === 401) {
              if (resp.data.detail.indexOf('validateCode') > -1) {
                // this.$alert('登录失败，验证码不正确')
              } else {
                // this.$alert('登录失败，用户名或密码不正确')
              }
              this.submitLoad = false
            } else {
              this.$alert('登录时发生错误，请稍候再试')
              this.submitLoad = false
              // console.log('login response:', resp)
            }
            // console.log('err', err)
          })
          // console.log('login ret is:', typeof ret, ret)

          // } catch (ex) {
          //   if (ex.status === 401) {
          //     this.$alert('用户名或密码不正确')
          //   } else {
          //     this.$alert('登录时发生错误，请稍候再试')
          //   }
          // }
        })
      }
    }
  }
</script>

<style lang="scss">
  .code_box {
    text-align: left;
    margin-left: 45px;
    font-size: 0;

    .el-form-item__error {
      left: 0px !important;
    }

    .el-input__inner {
      width: 240px !important;
    }
  }

  .code {
    width: 240px;
  }

  .code_img {
    width: 100px;
    height: 40px;
    background: transparent;
    display: inline-block;
    float: right;
    margin-right: 45px;
  }

  .login-wrap {
    position: relative;
    width: 100%;
    height: 100%;
    background: url(../../assets/login-bg2.jpg) no-repeat;
    background-size: cover;
    background-position: center center;

    .ms-title {
      position: absolute;
      top: 15%;
      font-size: 32px;
      color: #fff;
      left: 12%;
      letter-spacing: 4px;

    }

    .ms-login {
      position: absolute;
      right: 10%;
      top: 50%;
      transform: translate(-10%, -50%);
      width: 448px;
      border-radius: 20px;
      border: solid 2px rgba(119, 187, 239, 0.3);
      padding-bottom: 40px;
      background: rgba(0, 0, 0, 0.2);
      text-align: center;
    }

    .ms-login h2 {
      font-size: 20px;
      line-height: 30px;
      letter-spacing: 1px;
      color: #ffffff;
      text-align: center;
      font-weight: normal;
      padding: 35px 0 28px 0;
    }

    .ms-login input {
      width: 358px;
      height: 42px;
      padding-left: 40px;
      border-radius: 5px;
      margin: 0 auto;
    }

    .phone input {
      background: url(../../assets/login-user.png) no-repeat;
      background-size: 18px 20px;
      background-position: 10px;
      background-color: #f0f0f0 !important;
    }

    .newpwd input {
      background: url(../../assets/login-pwd.png) no-repeat;
      background-size: 18px 20px;
      background-position: 10px;
      background-color: #f0f0f0 !important;
    }

    .vercode input {
      background: url(../../assets/login-msgcode.png) no-repeat;
      background-size: 18px 20px;
      background-position: 10px;
      background-color: #f0f0f0;
      width: 156px;
      float: left;
      margin-left: 43px;
      border-radius: 5px 0px 0px 5px;
    }

    .login-btn {
      text-align: center;
    }

    .login-btn button {
      width: 358px;
      height: 42px;
      background-color: #0062cd;
      border-radius: 5px;
      border: none;
      font-size: 14px;
      color: #fff;
      margin-top: 30px;
    }

    .login-pwd {
      width: 358px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .login-pwd .checkdiv {
      color: #ccc;
    }

    .login-pwd .forgetpwd {
      padding: 0;
      color: #fffefe;
      margin-top: 10px;
    }

    .ms-tips {
      position: absolute;
      bottom: 20px;
      left: 60px;
      font-size: 14px;
      letter-spacing: 0px;
      color: #bfddff;
    }

    .ms-tips img {
      width: 14px;
      float: left;
      position: relative;
      top: 3px;
      margin-right: 5px;
      height: 16px;
    }

    .el-form-item__content .el-form-item__error {
      left: 43px;
    }
  }
  .apply_box{
    text-align: left;
    color: #fff;
    width: 358px;
    margin: 10px auto ;
  }
</style>
